#include "sysmgr.h"
#include <stdlib.h>
#include <string.h>

// 全局系统管理实例
sysmgr_t *g_sysmgr = NULL;

bool sysmgr_init(void)
{
    // 分配内存
    g_sysmgr = (sysmgr_t *)malloc(sizeof(sysmgr_t));
    if (!g_sysmgr) {
        return false;
    }
    
    // 初始化结构体
    memset(g_sysmgr, 0, sizeof(sysmgr_t));
    g_sysmgr->state = SYSMGR_STATE_INIT;
    g_sysmgr->is_logged_in = false;
    g_sysmgr->auto_login = false;
    
    return true;
}

void sysmgr_set_user(const char *username, const char *password, uint8_t user_type)
{
    if (!g_sysmgr || !username || !password) {
        return;
    }
    
    // 保存用户信息
    strncpy(g_sysmgr->username, username, sizeof(g_sysmgr->username) - 1);
    strncpy(g_sysmgr->password, password, sizeof(g_sysmgr->password) - 1);
    g_sysmgr->user_type = user_type;
    g_sysmgr->is_logged_in = true;
    
    // 保存最后登录用户名
    strncpy(g_sysmgr->last_username, username, sizeof(g_sysmgr->last_username) - 1);
}

void sysmgr_clear_user(void)
{
    if (!g_sysmgr) {
        return;
    }
    
    // 清除用户信息
    memset(g_sysmgr->username, 0, sizeof(g_sysmgr->username));
    memset(g_sysmgr->password, 0, sizeof(g_sysmgr->password));
    g_sysmgr->user_type = 0;
    g_sysmgr->is_logged_in = false;
}

const char *sysmgr_get_username(void)
{
    if (!g_sysmgr || !g_sysmgr->is_logged_in) {
        return NULL;
    }
    return g_sysmgr->username;
}

const char *sysmgr_get_password(void)
{
    if (!g_sysmgr || !g_sysmgr->is_logged_in) {
        return NULL;
    }
    return g_sysmgr->password;
}

uint8_t sysmgr_get_user_type(void)
{
    if (!g_sysmgr || !g_sysmgr->is_logged_in) {
        return 0;
    }
    return g_sysmgr->user_type;
}

bool sysmgr_is_logged_in(void)
{
    if (!g_sysmgr) {
        return false;
    }
    return g_sysmgr->is_logged_in;
}

void sysmgr_set_state(sysmgr_state_t state)
{
    if (!g_sysmgr) {
        return;
    }
    g_sysmgr->state = state;
}

sysmgr_state_t sysmgr_get_state(void)
{
    if (!g_sysmgr) {
        return SYSMGR_STATE_ERROR;
    }
    return g_sysmgr->state;
}

void sysmgr_set_error(uint32_t error_code)
{
    if (!g_sysmgr) {
        return;
    }
    g_sysmgr->error_code = error_code;
    g_sysmgr->state = SYSMGR_STATE_ERROR;
}

uint32_t sysmgr_get_error(void)
{
    if (!g_sysmgr) {
        return 0;
    }
    return g_sysmgr->error_code;
}